package com.syp.lease.common.utils;

import com.syp.lease.common.exception.LeaseException;
import com.syp.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import java.security.Key;
import java.util.Date;
import java.util.Map;

public class JwtUtil {
    public static final Key ADMIN_SECRET_KEY = Keys.secretKeyFor(SignatureAlgorithm.HS256);
    public static final Key APP_SECRET_KEY = Keys.secretKeyFor(SignatureAlgorithm.HS256);

    public static String createToken(Key secretKey, long ttlMillis, Map<String, Object> claims) {
        //生成签名密钥
        //SecretKey key = Keys.hmacShaKeyFor(secretKey.getEncoded());
        //设置过期时间
        long expMillis = System.currentTimeMillis() + ttlMillis;
        //设置JWT的payload部分(body)
        String token = Jwts.builder()
                //setClaims(claims) 设置自定义的claims
                .setClaims(claims)
                //signWith(key) 设置签名密钥
                .signWith(secretKey)
                //setIssuedAt(new Date()) 设置JWT的过期时间
                .setExpiration(new Date(expMillis))
                .compact();
        return token;
    }

    public static Claims parseToken(Key secretKey, String token) {
        if (token == null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }
        try {
            Claims claims = Jwts.parserBuilder()
                    .setSigningKey(secretKey)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
            return claims;
        } catch (ExpiredJwtException e) {
            throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);
        } catch (JwtException e) {
            throw new LeaseException(ResultCodeEnum.TOKEN_INVALID);
        }
    }
}
